<template>
  <el-container>
    <el-header style="height:80px;">
      <el-form
        ref="form"
        label-width="80px"
        style="margin-top:20px;"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="角色名称：">
              <el-select
                v-model="search.cRoleName"
                clearable
                onselect="return"
                placeholder="全部"
              >
                <el-option
                  v-for="item in role"
                  :key="item.cRoleId"
                  :label="item.cRoleName"
                  :value="item.cRoleName"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="0">
              <el-button
                class="querybtn"
                type="primary"
                @click="query(search)"
                style="color: #606266;background-color: #fff;border-color: #dcdfe6;margin-left:10px;"
              >查询</el-button>
              <el-button
                type="primary"
                @click="addRole"
              >新增</el-button>
            </el-form-item>
            <el-dialog
              :title="title"
              :visible.sync="dialogFormVisible"
            >
              <el-form
                ref="editform"
                label-width="120px"
                :model="myrole"
                class="demo-ruleForm"
              >
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="角色名称：">
                      <el-input
                        v-model="myrole.cRoleName"
                        auto-complete="off"
                        maxlength="30"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :class=$.role_setting_panel>
                  <!-- <el-form-item :label="item.cPermissionName" v-for="(item,index) in permissions" :key="index"> -->
                  <!-- <el-checkbox-group v-model="sub" @change="ok">
                      <el-checkbox :label="citem.cDetailId" :value="citem.cPermissionId" name="type" v-for="citem in item.subDetail" :key="citem.cDetailId">{{citem.remarks}}</el-checkbox>
                    </el-checkbox-group> -->
                  <el-checkbox-group
                    v-model="checkList"
                    class="checkgroup"
                  >
                    <el-checkbox
                      :label="item.cPermissionId"
                      v-for="(item,index) in permissions"
                      :checked="isPermissionChecked(item.cPermissionId)"
                      :key="index"
                    >{{item.cPermissionName.replace('：','')}}</el-checkbox>
                  </el-checkbox-group>
                  <!-- </el-form-item> -->
                </el-row>
              </el-form>
              <div
                slot="footer"
                class="dialog-footer"
                style="text-align: center"
              >
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button
                  type="danger"
                  @click="save()"
                >保 存</el-button>
              </div>
            </el-dialog>
          </el-col>
        </el-row>
      </el-form>
    </el-header>
    <el-main style="height:800px;">
      <section class="contant_head">
        <span>图表
          <!-- <sub>Form</sub> -->
        </span>
      </section>
      <el-table
        :data="tableData"
        border
        style="width: 98%;margin:10px;text-align:center;"
        :header-cell-style="getRowClass"
      >
        <el-table-column
          prop="index"
          label="编号"
          height="200px"
          width="90"
        > </el-table-column>
        <el-table-column
          prop="cRoleName"
          label="角色名称"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
        ></el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="210"
        >
          <template slot-scope="scope">
            <!-- <el-button size="small" :id="gitButtonId(scope.$index+1)" class="edit-btn" @click="handleStop($event,scope.$index+1, scope.row)">
                <label v-if="scope.row.state==2">禁用</label>
                <label v-else>启用</label>
              </el-button> -->
            <el-button
              class="edit-btn"
              @click="handleEdit(scope.$index, scope.row)"
              size="medium"
            >
              <i></i>修改
            </el-button>
            <el-button
              class="edit-btn"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="scope.row.idnex>6"
              size="medium"
            >
              <i></i>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next"
          :total="total"
          style="float:right"
        >
        </el-pagination>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import { api } from "@/fetch/api";


export default {
  name: "role",
  data() {
    return {
      options: [
        {
          value: 1,
          label: "全选"
        },
        {
          value: 2,
          label: "启用"
        },
        {
          value: 3,
          label: "禁用"
        }
      ],
      startDate: null,
      sub: [],
      endDate: null,
      role: api.LocalStorageService.get("role"),
      //修改 jlq-2018-2-6
      permissions: [],
      tableData: [],

      editNum: null,
      dialogVisible: false,
      dialogTableVisible: false,
      dialogFormVisible: false,
      treeDetail: [],
      treePermissionId: [],
      currentPage: 1, //當前頁碼
      limit: 10,
      total: null,
      edit: false,
      checkList: [],
      search: {
        cEmail: "",
        cGroup: "",
        cJobnumber: "",
        cNickname: "",
        cOperatorId: 0,
        cOperatorUser: "",
        cPassword: "",
        cPhone: "",
        cUserId: 0,
        cUsername: "",
        createTime: "",
        endDate: "",
        limit: 0,
        offset: 0,
        remark: ""
      },
      user: {
        cEmail: "",
        cGroup: "",
        cJobnumber: "",
        cNickname: "",
        cOperatorId: 0,
        cOperatorUser: "",
        cPassword: "",
        cPhone: "",
        cUserId: 0,
        cUsername: "",
        createTime: "",
        endDate: "",
        limit: 0,
        offset: 0,
        remark: "",
        role: {
          cRoleId: 0,
          cRoleName: "",
          createTime: "",
          endDate: "",
          remark: "",
          rolepermissionlist: [
            {
              cPermissionDetailId: 0,
              cRoleId: 0,
              cRolePermissionId: 0,
              permissionDetai: {
                cDetailId: 0,
                cPermissionId: 0,
                cUrl: "",
                remark: ""
              }
            }
          ],
          startDat: "",
          state: 0,
          updateTime: ""
        },
        roleId: 0,
        startDate: "",
        state: 0,
        updateTime: ""
      },
      myrole: {
        cRoleId: "",
        cRoleName: "",
        createTime: "",
        endDate: "",
        remark: "",
        rolepermissionlist: [
          {
            cPermissionDetailId: 0,
            cRoleId: 0,
            cRolePermissionId: 0,
            permissionDetai: {
              cDetailId: 0,
              cPermissionId: 0,
              cUrl: "",
              remark: ""
            }
          }
        ],
        startDat: "",
        state: 0,
        updateTime: ""
      },
      params: [],
      title: "111"
    };
  },
  methods: {
    ok(e) {
      let rolepermissionlist = [];
      for (let i = 0; i < e.length; i++) {
        let aaa = {};
        aaa.cPermissionDetailId = e[i];
        // aaa.cRoleId = this.myrole.rolepermissionlist.cRoleId
        // aaa.cRolePermissionId = this.myrole.rolepermissionlist.cRolePermissionId
        aaa.permissionDetai = {};
        aaa.permissionDetai.cDetailId = e[i];
        aaa.permissionDetai.cPermissionId = "";
        aaa.permissionDetai.cUrl = "";
        aaa.permissionDetai.remark = "";
        rolepermissionlist.push(aaa);
      }
      this.myrole.rolepermissionlist = rolepermissionlist;
      // this.myrole.rolepermissionlist = e
    },
    addRole() {
      // 新增角色
      this.sub = [];
      Object.keys(this.myrole).forEach(item => {
        if (
          Object.prototype.toString.call(this.myrole[item]) === "[object Array]"
        ) {
          this.myrole[item] = [];
        } else {
          this.myrole[item] = "";
        }
      });
      this.title = "添加";
      this.dialogFormVisible = true;
    },
    gitButtonId(index) {
      return index;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getUser(this.limit, val);
    },
    handleSizeChange(val) {
      this.limit = val;
      this.getUser(val, this.currentPage);
    },
    handleStop(e, index, row) {
      //调用数据库
      if (row.state == 2) {
        // document.getElementById(index).innerText = "启用";
        //更新状态
        this.user.cRoleId = row.cRoleId;
        this.user.state = 1;
      } else if (row.state == 1) {
        // document.getElementById(index).innerText = "禁用";
        this.user.cRoleId = row.cRoleId;
        this.user.state = 2;
      }
      api
        .RoleModifyStatus({ state: this.user.state, roleid: this.user.cRoleId })
        .then(response => {
          if (response.status === 100) {
            //如果成功
            this.getUser(10, this.currentPage);
          } else {
            this.$message.error(response.message);
          }
        });
    },
    handleDelete(index, row) {
      this.$confirm("是否继续删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          api
            .DeleteRole({
              roleid: row.cRoleId
            })
            .then(response => {
              if (response.status === 100) {
                this.$message.success(response.message);
                this.getUser(this.limit, this.currentPage);
              } else {
              }
            });
        })
        .catch(() => { });
    },
    handleEdit(index, row) {
      api.RoleSeacrch({ roleid: row.cRoleId }).then(response => {
        if (response.status === 100) {
          this.myrole = JSON.parse(JSON.stringify(row)); // 断开关联
          let roleArray = [];
          for (let i = 0; i < response.result.length; i++) {
            roleArray.push(response.result[i].cPermissionDetailId);
          }
          // this.sub = roleArray;
          this.checkList = roleArray;
          this.editNum = index;
          this.title = "修改";
          this.dialogFormVisible = !this.dialogFormVisible;
        }
      });
    },
    curry(e, node) {
      if (e.target.checked) {
        node.subDetail.forEach((sub, i) => {
          node.subDetail[i].checked = true;
        });
      } else {
        node.subDetail.forEach((sub, i) => {
          node.subDetail[i].checked = false;
        });
      }
    },
    isPermissionChecked(id) {
      return this.sub.some(item => item === id)
    },
    getPermissionDetail() {
      api
        .PermissionPage({}, { limit: 0, pageIndex: 0 })
        .then(response => {
          if (response.status === 100) {
            this.permissions = response.result;
            this.myrole.rolepermissionlist = response.result;
            api.LocalStorageService.update("permissions", response.result);
          } else {
            this.$message.error(response.message);
          }
        })
        .catch(error => {
          this.$message.error(error);
        });
    },
    getUser(limit, pageIndex) {
      api
        .RolePage(this.search, { limit: limit, pageIndex: pageIndex })
        .then(response => {
          if (response.status === 100) {
            this.tableData = response.result.list;
            this.tableData.forEach(function (item, index) {
              item.index = index + 1 + (pageIndex - 1) * limit;
            });
            this.total = response.result.total;
          } else {
            this.$message.error(response.message);
          }
        });
    },
    getRole() {
      api
        .RolePage({}, { limit: 10, pageIndex: 1 })
        .then(response => {
          if (response.status === 100) {
            // let data = [
            //   {
            //     cRoleName: "",
            //     cRoleId: ""
            //   }
            // ];
            this.role = data.concat(response.result.list);
            api.LocalStorageService.update("role", response.result.list);
          } else {
            this.$message.error(response.message);
          }
        })
        .catch(error => {
          this.$message.error(error);
        });
    },
    getRowClass({ row, column, rowIndex, columnIndex }) {
      if (rowIndex == 0) {
        return "background:rgba(242,242,242,1)";
      } else {
        return "";
      }
    },
    query(search) {
      search.endDate = this.endDate
        ? new Date(this.endDate).format("yyyy-MM-dd")
        : null;
      search.startDate = this.startDate
        ? new Date(this.startDate).format("yyyy-MM-dd")
        : null;

      api.RolePage(search, { limit: 10, pageIndex: 1 }).then(response => {
        if (response.status === 100) {
          this.tableData = response.result.list;
          this.currentPage = 1;
          this.tableData.forEach(function (item, index) {
            item.index = index + 1;
          });
          this.total = response.result.total;
        } else {
          this.$message.error(response.message);
        }
      });
    },
    save() {
      if (!this.myrole.cRoleName) {
        this.$message.error("角色名称不能为空！！！")
      } else if (!this.checkList.length) {
        this.$message.error("权限最少选择一个");
      } else if (this.myrole.cRoleId !== "") {
        const data = { ...this.myrole }
        const idList = []
        this.checkList.map(item => {
          idList.push({
            cPermissionDetailId: item,
            cRoleId: 0,
            cRolePermissionId: 0,
            permissionDetail: {
              cDetailId: 0,
              cPermissionId: 0,
              cUrl: "",
              remark: ""
            }
          })
        })
        data.rolepermissionlist = [...idList]
        api.RoleModify(data).then(response => {
          if (response.status === 100) {
            this.$message.success("修改成功");
            this.dialogFormVisible = !this.dialogFormVisible;
            this.getUser(10, this.currentPage);
          } else {
            this.$message.error(response.message);
          }
        });
        // 此处是修改保存
        // alert("修改保存");
      } else {
        if (!this.checkList.length) {
          this.$message.error("权限最少选择一个");
        } else if (this.myrole.cRoleName == "") {
          this.$message.error("角色名称不能为空");
        } else {
          const data = { ...this.myrole }
          const idList = []
          this.checkList.map(item => {
            idList.push({
              cPermissionDetailId: item,
              cRoleId: 0,
              cRolePermissionId: 0,
              permissionDetail: {
                cDetailId: 0,
                cPermissionId: 0,
                cUrl: "",
                remark: ""
              }
            })
          })
          data.rolepermissionlist = [...idList]
          api.RoleAdd(data).then(response => {
            if (response.status === 100) {
              this.$message.success("添加成功");
              this.dialogFormVisible = !this.dialogFormVisible;
              this.getUser(10, this.currentPage);
            } else {
              this.$message.error(response.message);
            }
          });
        }
      }
    }
  },
  mounted() {
    //修改-2018-2-6
    // this.getPermission();
    this.getRole();
    this.getPermissionDetail();
    this.getUser(10, this.currentPage);
  }
};
</script>

<style lang="less" scoped>
@import url("../../assets/css/index.css");
.el-header {
  width: 98%;
  background: #fff;
  margin: 0 auto;
  margin-top: 20px;
  margin-bottom: 20px;
  .el-input,
  .el-select,
  .el-date-picker {
    width: 100%;
  }
}
.el-main {
  width: 98%;
  background: #fff;
  margin: 0 auto;
  padding: 0px;
  .contant_head {
    border-left: 3px solid #f7585d;
    background: #f9f9f9;
    height: 40px;
    span {
      line-height: 40px;
      font-size: 20px;
      padding-left: 10px;
      sub {
        font-size: 12px;
      }
    }
  }
}
</style>
<style>
.cell {
  text-align: center;
}
</style>
<style lang="stylus" module="$">
.role_setting_panel {
  :global {
    .el-form-item {
      display: block;
    }
  }
}

.role_warpper {
  :global {
    .el-dialog__header {
      background: rgba(242, 242, 242, 1);
      padding-bottom: 16px;
    }

    .el-dialog__title {
      font-weight: bold;
    }

    .el-form-item__label {
      float: none;
      display: inline-block;
      min-width: 120px;
    }

    .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
      background-color: #F7585D;
      border-color: #F7585D;
    }

    .el-checkbox__input.is-checked+.el-checkbox__label {
      color: #F7585D;
    }

    .el-button--primary {
      color: #fff;
      background-color: #F7585D;
      border-color: #F7585D;
    }
  }
}
</style>
<style scoped>
.checkgroup {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: start;
  padding-left: 50px;
}

.checkgroup label {
  margin-left: 0;
  flex-basis: 30%;
  margin: 16px;
}
</style>
